package com.android.aishangauction.activity.mine;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.android.aishangauction.R;
import com.android.aishangauction.app.BaseActivity;
import com.android.aishangauction.model.data;
import com.android.aishangauction.model.dataCallback;
import com.android.aishangauction.model.detail.DeleteAddressData;
import com.android.aishangauction.model.detail.DeleteAddressDataCallback;
import com.android.aishangauction.model.member.AddressAreaData;
import com.android.aishangauction.model.member.AddressAreaDataCallback;
import com.android.aishangauction.utils.ConstantsUrl;
import com.android.aishangauction.utils.HttpUtils;
import com.android.aishangauction.utils.MyLog;
import com.android.aishangauction.utils.ObjectUtils;
import com.android.aishangauction.view.dialog.AddressPop;
import com.android.aishangauction.view.dialog.MainMsg;

import java.util.ArrayList;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * Created by Administrator on 2017/9/6.
 */

public class EditAddressActivity  extends BaseActivity {
    private Activity mcontext;
    private boolean isEdit;
    @BindView(R.id.main_top_title_delete)
    TextView maintop_title_delete;
    @BindView(R.id.add_detailname)
    EditText add_detailname;
    @BindView(R.id.add_detailaddress_phone)
    EditText add_detailaddress_phone;
    @BindView(R.id.add_detailaddress)
    EditText add_detailaddress;
    @BindView(R.id.add_detailaddress_province)
    TextView add_detailaddress_province;
    @BindView(R.id.add_detailaddress_city)
    TextView add_detailaddress_city;
    @BindView(R.id.add_detailaddress_county)
    TextView add_detailaddress_county;
    @BindView(R.id.province_ll)
    LinearLayout province_ll;
    @BindView(R.id.city_ll)
    LinearLayout city_ll;
    @BindView(R.id.county_ll)
    LinearLayout county_ll;
    private String name;
    private String phone;
    private String addressdetail;
    private String province;
    private String city;
    private String county;
    private String id="";
    private boolean networkConnected;
    private AddressPop pop;
    private int casCade=0;
    private String currently_id = "1";
    AlertDialog dialog;
    private ArrayList<AddressAreaData.DataBean> addressdata1 = new ArrayList<>();
    private ArrayList<AddressAreaData.DataBean> addressdata2 = new ArrayList<>();
    private ArrayList<AddressAreaData.DataBean> addressdata3 = new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_editaddress);
        mcontext=this;
        ButterKnife.bind(this);
        isEdit = getIntent().getBooleanExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_ISEDIT,false);
        id = getIntent().getStringExtra("addressdetail_id");
        name =  getIntent().getStringExtra("addressdetail_name");
        phone =  getIntent().getStringExtra("addressdetail_phone");
        addressdetail =  getIntent().getStringExtra("addressdetail");
        add_detailname.setText(name);
        add_detailaddress_phone.setText(phone);
        add_detailaddress.setText(addressdetail);
        if(isEdit) {
            maintop_title_delete.setVisibility(View.GONE);
        }
         else
        {
            maintop_title_delete.setVisibility(View.VISIBLE);
        }
    }
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    province = (String)msg.obj;
                    add_detailaddress_province.setText(province);
                    break;
                case 2:
                    city = (String)msg.obj;
                    add_detailaddress_city.setText(city);
                    break;
                case 3:
                    county = (String)msg.obj;
                    add_detailaddress_county.setText(county);
                    break;
                default:
                    break;
            }
        };
    };
    @OnClick({R.id.main_top_back, R.id.province_ll, R.id.city_ll, R.id.county_ll,R.id.complete,R.id.main_top_title_delete})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.main_top_back:
                finish();
                break;
            case R.id.main_top_title_delete:
                final MainMsg mainMsg = new MainMsg(mcontext);
                mainMsg.show(mcontext.getWindow().getDecorView(), 0, "是否删除该地址？");
                mainMsg.setOnSetSureClickListener(new MainMsg.OnSetSureClickListener() {
                    @Override
                    public void onSure() {
                        Delete();
                        mainMsg.close();
                    }
                });
                break;
            case R.id.complete:
                String name = add_detailname.getText().toString().trim();
                String phone = add_detailaddress_phone.getText().toString().trim();
                String address =  add_detailaddress.getText().toString().trim();
                String province = add_detailaddress_province.getText().toString().trim();
                String city = add_detailaddress_city.getText().toString().trim();
                String county = add_detailaddress_county.getText().toString().trim();
                if ("".equals(name)) {
                    ObjectUtils.toast(this, "请输入名字");
                    return;
                }
                if ("".equals(phone)) {
                    ObjectUtils.toast(this, "请输入手机号");
                    return;
                }
                if ("".equals(address)) {
                    ObjectUtils.toast(this, "请输入详细地址");
                    return;
                }
                if ("".equals(province)) {
                    ObjectUtils.toast(this, "请选择省份");
                    return;
                }
                if(city_ll.isShown()) {
                    if ("".equals(city)) {
                        ObjectUtils.toast(this, "请选择城市");
                        return;
                    }
                }
                if(county_ll.isShown()) {
                    if ("".equals(county)) {
                        ObjectUtils.toast(this, "请选择县区");
                        return;
                    }
                }
                Add(name,phone,address);
                break;
            case R.id.province_ll:
                casCade = 0;
                add_detailaddress_city.setText("");
                add_detailaddress_county.setText("");
                GetDataListData("1");
                break;
            case R.id.city_ll:
                casCade = 1;
                showRuleDialog();
                break;
            case R.id.county_ll:
                casCade = 2;
                showRuleDialog();
                break;
        }
    }
    //添加地址
    private void Add(String name,String phone,String addressdetail) {
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        String address =  ConstantsUrl.domain+ConstantsUrl.MEMBERADDRESSUPDATE;
        MyLog.e("地址", address);
        if (networkConnected) {
            HashMap<String, String> header = ObjectUtils.getHeader(mcontext);
            HashMap<String, String> map = new HashMap<>();
            map.put("id","");
            map.put("name",name);
            map.put("mobile",phone);
            map.put("address",addressdetail);
            map.put("zone",currently_id);
            HttpUtils.post(address, header,map, new dataCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {
                            ObjectUtils.toast(mcontext,e.getMessage());
                        }

                        @Override
                        public void onResponse(data response, int id) {

                            if (response.getCode() == 0) {
                                finish();
                                ObjectUtils.toast(mcontext, "添加地址成功");
                            } else {
                                if(response.getCode() == 40001){
                                    ObjectUtils.reLogin(mcontext);
                                }

                            }

                        }
                    }

            );
        } else {

            ObjectUtils.toast(mcontext, "网络连接出现异常");
        }
    }
    //删除地址
    private void Delete(){
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        String address =  ConstantsUrl.domain+ConstantsUrl.MEMBERADDRESSDETELE;
        MyLog.e("地址", address);
        if (networkConnected) {
            HashMap<String, String> header = ObjectUtils.getHeader(mcontext);
            HashMap<String, String> map = new HashMap<>();
            map.put("id",id);
            HttpUtils.get(address, header,map, new DeleteAddressDataCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {
                            ObjectUtils.toast(mcontext,e.getMessage());
                        }

                        @Override
                        public void onResponse(DeleteAddressData response, int id) {

                            if (response.getCode() == 0) {
                                ObjectUtils.toast(mcontext, "删除成功");
                                finish();
                            } else {
                                if(response.getCode() == 40001){
                                    ObjectUtils.reLogin(mcontext);
                                }
                            }

                        }
                    }

            );
        } else {
            ObjectUtils.toast(mcontext, "网络连接出现异常");
        }
    }
    //获取地址列表数据
    private void GetDataListData(final String parentid) {

        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        String address = ConstantsUrl.domain+ ConstantsUrl.MEMBERGETAREA;
        MyLog.e("地址", address);
        if (networkConnected) {
            HashMap<String, String> header = ObjectUtils.getHeader(mcontext);
            HashMap<String, String> map = new HashMap<>();
            map.put("parentid",parentid);
            HttpUtils.get(address, header,map, new AddressAreaDataCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {
                        }

                        @Override
                        public void onResponse(AddressAreaData response, int id) {

                            if (response.getCode() == 0) {
                                if (response.getData() != null) {
                                    switch (casCade)
                                    {
                                        case  0:
                                            addressdata1.clear();
                                            addressdata1.addAll(response.getData());
                                            showRuleDialog();
                                            break;
                                        case  1:
                                            addressdata2.clear();
                                            city_ll.setVisibility(View.VISIBLE);
                                            county_ll.setVisibility(View.GONE);
                                            addressdata2.addAll(response.getData());
                                            break;
                                        case  2:
                                            addressdata3.clear();
                                            county_ll.setVisibility(View.VISIBLE);
                                            addressdata3.addAll(response.getData());
                                            break;
                                    }
                                } else {
                                    if(response.getCode() == 40001){
                                        ObjectUtils.reLogin(mcontext);
                                    }
                                }
                            } else {

                            }

                        }
                    }

            );
        } else {
            ObjectUtils.toast(mcontext, "网络连接出现异常");
        }
    }

    /**
     * 区域选择
     */
    public void showRuleDialog() {

        LayoutInflater inflater = (LayoutInflater) mcontext
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view  = inflater.inflate(R.layout.areaaddress, null);
        final ListView listview= ( ListView) view.findViewById(R.id.listview);
        listview.setAdapter(new BaseAdapter() {
            @Override
            public int getCount() {
                if(casCade==0)
                {
                    return addressdata1.size();
                }else  if(casCade==1)
                {
                    return addressdata2.size();
                }else
                {
                    return addressdata3.size();
                }
            }
            @Override
            public Object getItem(int i) {
                return null;
            }

            @Override
            public long getItemId(int i) {
                return i;
            }

            @Override
            public View getView(int i, View view, ViewGroup viewGroup) {
                if(view==null)
                {
                    view = getLayoutInflater().inflate(R.layout.item_area_address,null);
                }
                TextView v =(TextView) view.findViewById(R.id.text);
                switch (casCade) {
                    case 0:
                        v.setText(addressdata1.get(i).getName());
                        break;
                    case 1:
                        v.setText(addressdata2.get(i).getName());
                        break;
                    case 2:
                        v.setText(addressdata3.get(i).getName());
                        break;
                }

                return view;
            }
        });
        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, final int i, long l) {
                switch (casCade) {
                    case 0:
                        currently_id =addressdata1.get(i).getId();
                        break;
                    case 1:
                        currently_id =addressdata2.get(i).getId();
                        break;
                    case 2:
                        currently_id =addressdata3.get(i).getId();
                        break;
                }

                new Runnable() {
                    @Override
                    public void run() {
                        Message msg = new Message();
                        switch (casCade) {
                            case 0:
                                msg.what = 1;
                                msg.obj =addressdata1.get(i).getName();
                                casCade = 1;
                                add_detailaddress_city.setText("");
                                add_detailaddress_county.setText("");
                                GetDataListData(currently_id);
                                break;
                            case 1:
                                msg.what = 2;
                                msg.obj =addressdata2.get(i).getName();
                                casCade = 2;
                                add_detailaddress_county.setText("");
                                GetDataListData(currently_id);
                                break;
                            case 2:
                                msg.what = 3;
                                msg.obj =addressdata3.get(i).getName();
                                break;
                        }

                        mHandler.sendMessage(msg);
                    }
                }.run();
                dialog.dismiss();
            }
        });
        dialog = new AlertDialog.Builder(mcontext).create();
        dialog.setView(view);
        dialog.setCancelable(true);
        Window dialogWindow = dialog.getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = 100; // 宽度
        lp.width = 100; // 高度
        dialogWindow.setAttributes(lp);
        dialog.show();
    }

}